package m2_work;

import com.rabbitmq.client.*;

import java.io.IOException;

public class Consumer {
    public static void main(String[] args) throws Exception {
        ConnectionFactory connectionFactory = new ConnectionFactory();
        connectionFactory.setHost("192.168.64.140");
        connectionFactory.setPort(5672);
        connectionFactory.setUsername("admin");
        connectionFactory.setPassword("admin");

        Channel channel = connectionFactory.newConnection().createChannel();

        //定义队列
        channel.queueDeclare("task_queue", true, false, false, null);

        DeliverCallback deliverCallback = new DeliverCallback() {
            @Override
            public void handle(String s, Delivery delivery) throws IOException {
                String msg = new String(delivery.getBody());
                System.out.println("收到消息:"+msg);
                for (int i = 0; i < msg.length(); i++) {
                    if(msg.charAt(i) == '.'){
                        try {
                            Thread.sleep(1000);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                }

                //回执 -消息中的一串整数值
                //false - 是否同时确认以前收到的所有消息
                //channel.basicAck(回执, false);
                channel.basicAck(delivery.getEnvelope().getDeliveryTag(), false);

                System.out.println("消息处理结束");
            }
        };

        CancelCallback cancelCallback = new CancelCallback() {
            @Override
            public void handle(String s) throws IOException {

            }
        };

        //每次只抓取一条
        channel.basicQos(1);

        //消费数据,接收数据
        channel.basicConsume(
                "task_queue",
                false,          //ack回执,关闭自动确认,改成手动确认,false表示手动ack(收到回执才从服务器删除消息)
                deliverCallback,
                cancelCallback);
    }
}
